import org.json.simple.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.Socket;

/**
 * DebuggerTransport.java
 *
 * Copyright (C) 2013 Timo Tegtmeier.
 * All rights reserved.
 */

public class DebuggerTransport {

    private String host;
    private int port;

    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;

    public DebuggerTransport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public boolean open() {
        try {
            if(socket == null)
                socket = new Socket(host, port);
            if(inputStream == null)
                inputStream = socket.getInputStream();
            if(outputStream == null)
                outputStream = socket.getOutputStream();
            return true;
        } catch(IOException e) {
            return false;
        }
    }

    public void close() {
        try {
            if(inputStream != null)
                inputStream.close();
            if(outputStream != null)
                outputStream.close();
            if(socket != null)
                socket.close();
        } catch(IOException e) {
            // Silently ignore this
        }
    }

    public void sendMessage(String message) throws IOException {
        String data = String.format("%d:%s", message.length(), message);
        outputStream.write(data.getBytes());
        outputStream.flush();
    }

    public void sendMessage(JSONObject cmd) throws IOException {
        sendMessage(cmd.toJSONString());
    }

    public String receiveAnswer() throws IOException {
        int count = 0;
        while(inputStream.available() <= 0) ;
        byte[] cBuffer = new byte[1];
        do {
            inputStream.read(cBuffer);
            if(cBuffer[0] != ':')
                count = count * 10 + cBuffer[0] - '0';
        } while(cBuffer[0] != ':');

        byte[] buffer = new byte[count];
        StringWriter sw = new StringWriter();
        inputStream.read(buffer);
        sw.write(new String(buffer));
        sw.flush();
        return sw.toString();
    }
}
